<template>
    <div id="userLayout" class="w-full h-full relative">
        <div class="rounded-lg flex items-center justify-evenly w-full h-full md:w-screen md:h-screen md:bg-[#194bfb]">
            <div class="md:w-3/5 w-10/12 h-full flex items-center justify-evenly">
                <div class="oblique h-[130%] w-3/5 bg-white dark:bg-slate-900 transform -rotate-12 absolute -ml-52" />
                <div class="z-[999] pt-12 pb-10 md:w-96 w-full rounded-lg flex flex-col justify-between box-border">
                    <div>
                        <div class="flex items-center justify-center">
                            <img class="w-24" :src="$glbConfig.appLogo" />
                        </div>
                        <div class="mb-9">
                            <p class="text-center text-4xl font-bold">{{ $glbConfig.appName }}</p>
                            <p class="text-center text-sm font-normal text-gray-500 mt-2.5">跨度推是一体化，自动化运营产品</p>
                        </div>
                        <n-form v-show="!isShowWxQrcode" ref="formRef" class="mb-4" :size="formSize" :label-width="80" :model="formValue" :rules="rules"> 
                            <n-form-item label="手机号" path="phone">
                                <n-input
                                    :maxlength="11"
                                    clearable
                                    v-model:value="formValue.phone"
                                    :allow-input="onlyAllowNumber"
                                    placeholder="手机号"
                                />
                            </n-form-item>
                            <n-form-item label="密码" path="password">
                                <n-input
                                    :minlength="11"
                                    type="password"
                                    
                                    show-password-on="mousedown"
                                    v-model:value="formValue.password"
                                    placeholder="密码"
                                />
                            </n-form-item>
                            <n-form-item label="验证码" path="code">
                                <n-input
                                    clearable
                                    :minlength="4"
                                    :maxlength="4"
                                    
                                    v-model:value="formValue.code"
                                    :allow-input="onlyAllowNumber"
                                    placeholder="输入4位验证码"
                                />
                                <n-tooltip trigger="hover">
                                    <template #trigger>
                                        <n-image class="mx-1" style="width:60%" :img-props="{'style':'width:100%'}" :src="imgCodeUrl" alt="点击预览">
                                        </n-image>
                                    </template>
                                    
                                    点击查看验证码
                                  </n-tooltip>
                              
                                <n-button @click="getImgCode">换一个</n-button>
                            </n-form-item>
                            <div class="flex justify-end" style="height:40px">
                                <n-button
                                    text
                                    tag="a"
                                    target="_blank"
                                    type="primary"
                                    @click="isShowWxQrcode = true"
                                >
                                微信扫码登录
                            </n-button>
                            </div>
                            <n-form-item>
                                <n-button  attr-type="button" class="w-full my-3" @click.prevent="handleValidateClick"> 登录 </n-button>
                            </n-form-item>
                        </n-form>
                        <div  v-show="isShowWxQrcode" class="w-full  pb-7 mb-7 flex justify-center flex-col items-center">
                            <h3 style="font-size: 18px;"  class="mt-6 mb-2">
                                打开微信二维码扫一扫
                            </h3>
                            <img :src="wxQrcodeUrl" @click="getWxQrcode" class="my-5" style="height:260px;width:260px" />
                            <div class="flex justify-end" style="height:40px;width:100%">
                                <n-button
                                    text
                                    tag="a"
                                    target="_blank"
                                    type="primary"
                                    @click="isShowWxQrcode = false"
                                >
                                    手机号密码登录
                                </n-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="hidden md:block w-1/2 h-full float-right bg-[#194bfb]">
                <img class="h-full" src="@/assets/login_right_banner.jpg" alt="banner" />
            </div>
        </div>
        <BottomInfo class="left-0 right-0 absolute bottom-3 mx-auto w-full z-20">
            <div class="links items-center justify-center gap-2 hidden md:flex">
                <a href="http://doc.henrongyi.top/" target="_blank">
                    <!-- <img src="@/assets/docs.png" class="w-8 h-8" alt="文档" /> -->
                </a>
                <a href="https://support.qq.com/product/371961" target="_blank">
                    <!-- <img src="@/assets/kefu.png" class="w-8 h-8" alt="客服" /> -->
                </a>
                <a href="https://space.bilibili.com/322210472" target="_blank">
                    <!-- <img src="@/assets/video.png" class="w-8 h-8" alt="视频站" /> -->
                </a>
            </div>
        </BottomInfo>
    </div>
</template>

<script setup lang="ts">
    import BottomInfo from "@/components/bottomInfo/bottomInfo.vue";
    import type { FormItemRule, FormRules, FormInst } from "naive-ui";
    import {useUserStore,useAppStore} from "@/stores";
    import {loginApi,getImgCodeApi, getWxQrcodeApi} from "@/api/auth";
    const $store = useAppStore();
    const $msg = useMessage();
    const router = useRouter();
    const formSize = computed(()=>$store.isDeskTop ? "large" : "medium")
    const formRef = ref<FormInst | null>(null);
    const isShowWxQrcode = ref(true)
    const formValue = ref({
        phone: "",
        code: "",
        password:"",
    });
    const rules: FormRules = {
        password: {
            required: true,
            trigger: ["input"],
            min: 6,
            validator(rule: FormItemRule, value: string) {
                // 6位及以上
                if (!/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[a-z])\S*$/.test(value)) {
                    return new Error("密码必须包含数字和小写字母且长度在6位以上!");
                }
                return true;
            },
            key: "password"
        },
        phone: {
            required: true,
            trigger: ["input"],
            max: 11,
            validator(rule: FormItemRule, value: string) {
                if (!/^1[3-9]\d{9}$/.test(value)) {
                    return new Error("手机号码错误!");
                }
                return true;
            },
            key: "phone"
        },
        code: {
            max: 6,
            required: true,
            message: "请输入4位验证码",
            trigger: ["input"],
            key: "code"
        }
    };
    const userStore = useUserStore()
    const $router = useRouter()
    const handleValidateClick = () => {
      formRef.value?.validate((errors) => {
        if (!errors) {
          loginApi(formValue).then(res=>{
            if(res.data.code == 200){
              userStore.token = res.data.token
              // 登录成功后 获取用户信息，跳转到首页
              userStore.setUserInfo().then(res=>{
                $router.replace("/layout")
                $msg.success("登录成功!")
              })
            }else{
              $msg.error(res.data.msg)
            }
          }).catch(e=>{
            console.log(e)
          })
        } 
      });
    };
    const wxQrcodeUrl = ref("")
    let timer:NodeJS.Timeout | null = null
    let time1 = 30;
    const getWxQrcode = ()=>{
        if(timer){
            $msg.error(`剩余${time1}秒可切换`)
            return 
        }
        getWxQrcodeApi().then(res=>{
            wxQrcodeUrl.value = res.data
            timer = setInterval(()=>{
                if(time1 <= 1){
                    clearInterval(timer as NodeJS.Timeout)
                    timer = null
                    time1 = 30;
                    return 
                }
                time1 -= 1;
            },1000)
        }).catch(e=>{
            $msg.error("获取验证码失败,请稍后重试!")
        })
    }
    const imgCodeUrl = ref("")
    
    const getImgCode = ()=>{
        getImgCodeApi().then(res=>{
            imgCodeUrl.value = res.data.data
        }).catch(e=>{
            $msg.error("获取验证码失败,请稍后重试!")
        })
    }
    const onlyAllowNumber = (value: string) => !value || /^\d+$/.test(value);
    onMounted(() => {
        getWxQrcode()
    });
    watch(isShowWxQrcode,(v)=>{
        if(!v){
            // 如果显示了账号密码登录，并且没有imgCode 则获取新的
            imgCodeUrl.value || getImgCode()
        }
    })
</script>

<style>

</style>